package com.ld.web.test;

import com.baidu.aip.speech.AipSpeech;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class WavToWords {
    static private Logger logger = LoggerFactory.getLogger(WavToWords.class);

    /**
     * 音频文件频率8k转16k。必须要转，因为不转百度识别不出来，错误信息是音质太差
     *
     * @param sourceFile
     * @return
     */
    public static String cover8xTo16x(File sourceFile) {
        String targetPath = null;
        //ffmpeg -y  -i 16k.wav  -acodec pcm_s16le -f s16le -ac 1 -ar 16000 16k.pcm

        //ffmpeg -y  -i aidemo.mp3  -acodec pcm_s16le -f s16le -ac 1 -ar 16000 16k.pcm
        //// -acodec pcm_s16le pcm_s16le 16bits 编码器
        //// -f s16le 保存为16bits pcm格式
        //// -ac 1 单声道
        ////  -ar 16000  16000采样率
        try {
            File ffmpegPath = new File("/usr/local/Cellar/ffmpeg/4.2.2_2/bin/ffmpeg"); //存放ffmpeg程序的目录
            targetPath = sourceFile.getAbsolutePath().replaceAll(".wav", "_16x.pcm");
//            File ffmpegPatha = new File(targetPath);
//            if(ffmpegPatha.exists()){
//                ffmpegPatha.delete();
//            }
            // ffmpeg.exe -i source.wav -ar 16000 target.wav
            List<String> wavToPcm = new ArrayList<String>();
            wavToPcm.add(ffmpegPath.getAbsolutePath());
            wavToPcm.add("-y");
            wavToPcm.add("-i");
            wavToPcm.add(sourceFile.getAbsolutePath());
            wavToPcm.add("-acodec");
            wavToPcm.add("pcm_s16le");
            wavToPcm.add("-f");
            wavToPcm.add("s16le");
            wavToPcm.add("-ac");
            wavToPcm.add("1");
            wavToPcm.add("-ar");
            wavToPcm.add("16000");
            wavToPcm.add(targetPath);
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(wavToPcm);
            builder.redirectErrorStream(true);
            Process process = builder.start();
            process.waitFor();
        } catch (Exception e) {
            logger.error("录音文件8k转化16k失败" + e.getMessage());
            e.printStackTrace();
            return null;
        }
        File ffmpegPatha = new File(targetPath);
        if (ffmpegPatha.exists()) {
            return targetPath;
        }
        logger.error("传入的文件路径有误");
        return null;
    }

    public static void test() {
        File file = new File("/Users/xxx/gitHome/https/demo/record-cut_50_100.wav");

        String resultPath = cover8xTo16x(file);
        AipSpeech client = new AipSpeech("18587989", "kQ0IG5FfcHuQGZVvioQf3qNu", "WfiV3HwHH1Z5gmvE9Iiw1xMdkzyhG89G");
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        JSONObject res = client.asr(resultPath, "wav", 16000, null);
        System.out.println(res);
    }

    public static void main(String[] args) {
        int a = 0;
        for (int i = 0; i < 1000; i++) {

            File file = new File("/Users/xxx/gitHome/https/demo/record-cut_" + a + "_" + (a + 50) + ".wav");
            if (!file.exists()) {
                break;
            }
            String resultPath = cover8xTo16x(file);
            if(StringUtils.isBlank(resultPath)){
                break;
            }
            AipSpeech client = new AipSpeech("18587989", "kQ0IG5FfcHuQGZVvioQf3qNu", "WfiV3HwHH1Z5gmvE9Iiw1xMdkzyhG89G");
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);
            JSONObject res = client.asr(resultPath, "pcm", 16000, null);
            if (res.getString("err_msg").equals("success.")) {
                JSONArray aaa = (JSONArray) res.get("result");
                System.out.println("第" + i + "段：" + aaa.get(0));
                file = new File("结果.docx");
                try {
                    Thread.sleep(1000);
                    //if file doesnt exists, then create it
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //true = append file
                    FileWriter fileWritter = new FileWriter(file.getName(), true);
                    fileWritter.write(aaa.get(0)+"");
                    fileWritter.close();
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                logger.warn(res.toString());
            }
            a = a + 50;
        }
    }
}
